<script setup>
import { ref } from 'vue'
import { Button, Field } from 'vant'
import { useRouter } from 'vue-router'
import { apiLogin } from '../api/user' // 引入登录接口

const router = useRouter()
const form = ref({
  username: '',
  password: ''
})
const errorMsg = ref('')

const handleLogin = async () => {
  try {
    const res = await apiLogin(form.value) // 调用登录接口
    localStorage.setItem('userId', res.userId) // 存储登录凭证
    router.push('/home') // 跳转首页
  } catch (err) {
    errorMsg.value = err.message // 显示错误信息
  }
}

const toRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="logo">
      <img src="" alt="商城logo" />
    </div>
    <div class="form-wrap">
      <Field
        v-model="form.username"
        placeholder="请输入手机号/邮箱"
        clearable
        left-icon="user"
      />
      <Field
        v-model="form.password"
        placeholder="请输入密码"
        type="password"
        clearable
        left-icon="lock"
      />
      <Button type="primary" @click="handleLogin" class="login-btn">登录</Button>
      <div class="link-wrap">
        <span @click="toRegister">立即注册</span>
        <span>忘记密码？</span>
      </div>
    </div>
    <div class="error-tip" v-if="errorMsg">{{ errorMsg }}</div>
  </div>
</template>

<style scoped lang="scss">
.login-container {
  min-height: 100vh;
  padding: 0 1.5rem;
  background: #f8f8f8;

  .logo {
    padding: 4rem 0;
    text-align: center;
    img {
      width: 6rem;
      height: 6rem;
      border-radius: 1rem;
    }
  }

  .form-wrap {
    background: white;
    border-radius: 0.8rem;
    padding: 1.5rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);

    .login-btn {
      margin: 1.5rem 0;
      height: 2.8rem;
      font-size: 0.9rem;
    }

    .link-wrap {
      display: flex;
      justify-content: space-between;
      font-size: 0.8rem;
      color: #666;
    }
  }
  .error-tip {
    color: #ff4d4f;
    font-size: 0.8rem;
    text-align: center;
    margin-top: 0.5rem;
  }
}
</style>